<?php
namespace Manage\Controller;
use Think\Controller;

/**
 * Class AdminCsdtGateController
 * @package Manage\Controller
 * 调蓄池闸门
 */
class AdminCsdtGateController extends Controller {

    private $model_name = 'CsdtGate';
    private $record_model = 'CsdtGateRecord';

    public function index(){
        $this->display();
    }

    public function get_all(){
        if(!I('get.gen')){
            $list = get_date_grid($this->model_name);
        }else{
            $map = array_merge(get_page_query_map(I('get.')), get_page_query_map(I('post.')));
            $page = max(I('get.page'), 1);
            $rows_num = get_kv_val('admin_page_list_num')?get_kv_val('admin_page_list_num'):I('get.rows');
            $list = D($this->model_name)->gen_search($map, $page, $rows_num);
        }
        echo json_encode($list);
    }

    public function add(){
        $model = D($this->model_name);
        if(IS_POST){
            $data = filterInput($_POST);
            $model->addObj($data, 'id');
            echo json_encode(array('status'=>1,'msg'=>'保存成功！'));
            return;
        }
    }

    public function edit(){
        $model = D($this->model_name);
        if(IS_POST){
            $post_data = filterInput($_POST);
            $model->save($post_data);
            echo json_encode(array('status'=>1,'msg'=>'保存成功！'));
            return;
        }
    }

    public function deleteArray(){
        $data = filterInput($_POST);
        $ids = $data['ids'];
        $model = D($this->model_name);
        $item = $model->deleteArray($ids);
        if($item){
            echo json_encode(array('status'=>1));
        }else{
            echo json_encode(array('status'=>0));
        }
    }

    public function log_index(){
        $this->display();
    }

    public function log_get_all(){
        $list = get_date_grid($this->record_model);
        echo json_encode($list);
    }

    public function log_add(){
        $model = D($this->record_model);
        if(IS_POST){
            $data = filterInput($_POST);
            $model->addObj($data, 'id');
            echo json_encode(array('status'=>1,'msg'=>'保存成功！'));
            return;
        }
    }

    public function log_edit(){
        $model = D($this->record_model);
        if(IS_POST){
            $post_data = filterInput($_POST);
            $model->save($post_data);
            echo json_encode(array('status'=>1,'msg'=>'保存成功！'));
            return;
        }
    }

    public function log_deleteArray(){
        $data = filterInput($_POST);
        $ids = $data['ids'];
        $model = D($this->record_model);
        $item = $model->deleteArray($ids);
        if($item){
            echo json_encode(array('status'=>1));
        }else{
            echo json_encode(array('status'=>0));
        }
    }

    public function get_obj_json(){
        $id = I('get.id');
        $obj = D($this->model_name)->queryObj($id, 'id');
        echo $obj?json_encode($obj):json_encode(array('status'=> -1));
    }

    public function get_obj_log_json(){
        $id = I('get.id');
        $obj = D($this->record_model)->queryObj($id, 'id');
        $station_model = D('Csdt');
        $num_model = D($this->model_name);
        $num = $num_model->queryObj($obj['gateid'], 'id');
        $obj['num'] = $num['gate_name'];
        $station = $station_model->queryObj($num['ps_id'], 'id');
        $obj['station'] = $station['id'];
        echo $obj?json_encode($obj):json_encode(array('status'=> -1));
    }

    public function get_all_gate(){
        $pumpid = I('get.ps_id');
        if(!$pumpid){
            $list = D($this->model_name)->getAll();
        }else{
            $ids = explode(',', $pumpid);
            $list = array();
            foreach($ids as $id){
                $temp = D($this->model_name)->queryField('ps_id', $id);
                if($temp||!empty($temp)){
                    $list = array_merge($list, $temp);
                }
            }
        }
        $list = stations_add_all_text($list, 'gate_name');
        echo json_encode($list);
    }

    public function set_check(){
        D($this->record_model)->checked_record(I('post.ids'));
        echo json_encode(array('status'=> 1));
    }

    public function just_see(){
        $this->display();
    }

    public function just_see_fy(){
        $id = I('get.id');
        $fy = D($this->model_name)->queryObj($id, 'id');
        $this->assign('fy', $fy);
        $this->display();
    }

    public function export_record(){
        header("Content-type: text/html; charset=utf-8");
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Reader.Excel5");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");
        $art = array(
            'station' => 'Csdt',
            'pid_field' => 'ps_id',
            'record_pid_field' => 'gateid',
            'sta_name_field' => 'ps_name',
        );
        $pid = I('get.pid')?I('get.pid'):0;
        $start = I('get.start')?I('get.start'):'2016-01-01 00:00:00';
        $end = I('get.end')?I('get.end'):'2016-12-31 00:00:00';
        $str = '((gate_start >= \''.$start.'\' AND gate_start <= \''.$end.'\') OR
        (gate_start <= \''.$start.'\' AND gate_off >= \''.$end.'\') OR
        (gate_off >= \''.$start.'\' AND gate_off <= \''.$end.'\')
        OR (gate_off is null AND gate_start <=  \''.$end.'\'))';
        $station_model = D($art['station']);
        $fy_model = D($this->model_name);
        $record_model = D($this->record_model);
        $temp_file = './excelfile/csdtgate.xls';
        $out_file_name = '闸门运行记录';
        $php_reader = new \PHPExcel_Reader_Excel5();
        $filename = file_zh_cn_icvon($temp_file);
        if(!$php_reader->canRead($filename)){
            echo '无法识别的Excel文件！';
            return false;
        }
        $php_excel = $php_reader->load($filename);
        $pids = explode(',', $pid);
        $index = 0;
        foreach($pids as $pid){
            $station = $station_model->queryObj($pid, 'id');
            $new_sheet = new \PHPExcel_Worksheet($php_excel); //创建一个工作表
            $php_excel->addSheet($new_sheet); //插入工作表
            $php_excel->setActiveSheetIndex($index);
            $currentSheet = $php_excel->getActiveSheet($index);
            $currentSheet->setTitle($station['ps_name']);
            $start_row = 6;
            $row = $start_row;
            $fys = $fy_model->queryField($art['pid_field'],$station['id']);
            $currentSheet->setCellValue('A1',$station[$art['sta_name_field']].$out_file_name);
            $index_num = 1;
            $check_text = '';
            foreach($fys as $fy){
                $map[$art['record_pid_field']] = array('eq', $fy['id']);
                $list = $record_model->where($map)->where($str)->order('date desc')->select();
                $list = $record_model->bz_record($fy, $list, $start, $end);
                $check_text = records_check_status($list);
                foreach($list as $k => $record){
                    $currentSheet->setCellValue('A'.$row,$index_num++);
                    $currentSheet->setCellValue('B'.$row,$fy['gate_name']);
                    $currentSheet->setCellValue('C'.$row,$record['gate_start']);
                    $currentSheet->setCellValue('D'.$row,$record['gate_startwaterline']);
                    $currentSheet->setCellValue('E'.$row,$record['gate_off']);
                    $currentSheet->setCellValue('F'.$row,$record['gate_offwaterline']);
                    $currentSheet->setCellValue('G'.$row,round($record['time'],2));
                    $currentSheet->setCellValue('H'.$row,$record['opr']);
//                $currentSheet->setCellValue('I'.$row,$record['weather']);
                    $currentSheet->setCellValue('J'.$row,$record['gate_reson']);
                    $currentSheet->setCellValue('K'.$row,$record['gate_height']);
                    $row++;
                }
            }
            //设定一级表头
            $currentSheet->mergeCells('A1:L3');
            $currentSheet->setCellValue('A1', $station['ps_name'].'进水闸门运行记录'.'('.$check_text.')');
            $currentSheet->getRowDimension(1)->setRowHeight(35);
            $currentSheet->getStyle('A1')->getFont()->setName('宋体');
            $currentSheet->getStyle('A1')->getFont()->setSize(24);
            $currentSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $currentSheet->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            //设定二级表头
            $currentSheet->mergeCells('A4:A5');
            $currentSheet->setCellValue('A4', '序号');
            $currentSheet->mergeCells('B4:B5');
            $currentSheet->setCellValue('B4', '闸门  （编号）');
            $currentSheet->mergeCells('C4:C5');
            $currentSheet->setCellValue('C4', '开闸时间（年、月、日、时、分）');
            $currentSheet->mergeCells('D4:D5');
            $currentSheet->setCellValue('D4', '开闸时调蓄池水位');
            $currentSheet->mergeCells('E4:E5');
            $currentSheet->setCellValue('E4', '关闸时间（日、时、分）');
            $currentSheet->mergeCells('F4:F5');
            $currentSheet->setCellValue('F4', '关闸时调蓄池水位');
            $currentSheet->mergeCells('G4:G5');
            $currentSheet->setCellValue('G4', '累计进水时间      (开闸-关闸）');
            $currentSheet->mergeCells('H4:H5');
            $currentSheet->setCellValue('H4', '操作人员');
            $currentSheet->mergeCells('I4:I5');
            $currentSheet->setCellValue('I4', '天气情况（雨情）');
            $currentSheet->mergeCells('J4:J5');
            $currentSheet->setCellValue('J4', '开闸原因');
            $currentSheet->mergeCells('K4:K5');
            $currentSheet->setCellValue('K4', '开闸高度');
            $currentSheet->mergeCells('L4:L5');
            $currentSheet->setCellValue('L4', '备注');
            $currentSheet->getStyle('A'.$start_row.':L'.$row)->getFont()->setName('宋体');
            $currentSheet->getStyle('A'.$start_row.':L'.$row)->getFont()->setSize(11);
            $currentSheet->getStyle('A'.$start_row.':L'.$row)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $currentSheet->getStyle('A'.$start_row.':L'.$row)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $currentSheet->getStyle('A1:L'.$row)->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $currentSheet->getColumnDimension('A')->setWidth(12);
            $currentSheet->getColumnDimension('B')->setWidth(16);
            $currentSheet->getColumnDimension('C')->setWidth(20);
            $currentSheet->getColumnDimension('D')->setWidth(16);
            $currentSheet->getColumnDimension('E')->setWidth(20);
            $currentSheet->getColumnDimension('F')->setWidth(16);
            $currentSheet->getColumnDimension('G')->setWidth(12);
            $currentSheet->getColumnDimension('H')->setWidth(12);
            $currentSheet->getColumnDimension('I')->setWidth(12);
            $currentSheet->getColumnDimension('J')->setWidth(12);
            $currentSheet->getColumnDimension('K')->setWidth(15);
            $index++;
        }

        $php_writer = new \PHPExcel_Writer_Excel5($php_excel);
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        $out = substr($start,0,10).'/'.substr($end,0,10).'_'.$station[$art['sta_name_field']].$out_file_name;
        header("Content-Disposition: attachment;filename=".$out.".xls");
        header('Cache-Control: max-age=0');
        $php_writer->save('php://output');
    }

    public function import(){
        header("Content-type: text/html; charset=utf-8");
        $filename = '.'.I('get.file_path');
        $start_row = 2;
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Reader.Excel5");
        $php_reader = new \PHPExcel_Reader_Excel5();
        $filename = file_zh_cn_icvon($filename);
        $php_excel = $php_reader->load($filename);

        $station_model = D('Csdt');
        $model = D('CsdtGate');
        $p_model = D('CsdtMachine');
        for($sheet_index=0;$sheet_index<1;$sheet_index++){
            $currentSheet = $php_excel->getSheet($sheet_index);
            $allRow = $currentSheet->getHighestRow();
            for($currentRow = $start_row;$currentRow <= $allRow;$currentRow++){
                $map['ps_name'] = array('eq', $currentSheet->getCell('A'.$currentRow)->getValue());
                $one = $station_model->where($map)->find();
                if(!$one){
                    $station_data = array();
                    $station_data['ps_name'] = $currentSheet->getCell('A'.$currentRow)->getValue();
                    $station_data['ps_catg1'] = 0;
                    $station_data['ps_catg2'] = 0;
                    $station_data['ps_catg3'] = 0;
                    $one = $station_model->add($station_data);
                }else{
                    $one = $one['id'];
                }
                $p_one = $p_model->queryObj($currentSheet->getCell('B'.$currentRow)->getValue(), 'scrmach_number');
                $fy_data = array();
                $fy_data['ps_id'] = $one;
                $fy_data['scrmach_id'] = $p_one?$p_one['id']:0;
                $fy_data['gate_id'] = $currentSheet->getCell('C'.$currentRow)->getValue();
                $fy_data['gate_name'] = $currentSheet->getCell('D'.$currentRow)->getValue();
                $fy_data['gate_typ'] = $currentSheet->getCell('E'.$currentRow)->getValue();
                $fy_data['gate_mfr'] = $currentSheet->getCell('F'.$currentRow)->getValue();
                $fy_data['gate_model'] = $currentSheet->getCell('G'.$currentRow)->getValue();
                $fy_data['gate_motor_power'] = $currentSheet->getCell('H'.$currentRow)->getValue();
                $fy_data['gata_elev'] = $currentSheet->getCell('I'.$currentRow)->getValue();
                $fy_data['gate_h'] = $currentSheet->getCell('J'.$currentRow)->getValue();
                $fy_data['gate_wid'] = $currentSheet->getCell('K'.$currentRow)->getValue();
                $fy_data['gate_cntl_typ'] = $currentSheet->getCell('L'.$currentRow)->getValue();
                $fy_data['gate_swit_sty'] = $currentSheet->getCell('M'.$currentRow)->getValue();
                $fy_data['gate_row_num'] = $currentSheet->getCell('N'.$currentRow)->getValue();
                $fy_data['gate_hole_num'] = $currentSheet->getCell('O'.$currentRow)->getValue();
                $fy_data['gate_svc_dt'] = $currentSheet->getCell('P'.$currentRow)->getValue();
                $model->add($fy_data);
            }
        }
        echo '导入完成';
    }

    public function export(){
        header("Content-type: text/html; charset=utf-8");
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Reader.Excel5");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");
        $temp_file = './exportexcel/gate.xls';
        $php_reader = new \PHPExcel_Reader_Excel5();
        $filename = file_zh_cn_icvon($temp_file);
        if(!$php_reader->canRead($filename)){
            echo '无法识别的Excel文件！';
            return false;
        }
        $php_excel = $php_reader->load($filename);
        $currentSheet = $php_excel->getSheet(0);
        $station_model = D('Csdt');
        $model = D('CsdtGate');
        $p_model = D('CsdtMachine');
        $list = $model->getAll();
        $currentRow = 2;
        foreach($list as $fy){
            $station = $station_model->queryObj($fy['ps_id'], 'id');
            if(!$station){
                continue;
            }
            $p_one = $p_model->queryObj($fy['scrmach_id'], 'id');
            $currentSheet->setCellValue('A'.$currentRow, $station['ps_name']);
            $currentSheet->setCellValue('B'.$currentRow, $p_one?$p_one['scrmach_number']:'');
            $currentSheet->setCellValue('C'.$currentRow, $fy['gate_id']);
            $currentSheet->setCellValue('D'.$currentRow, $fy['gate_name']);
            $currentSheet->setCellValue('E'.$currentRow, gate_typ($fy['gate_typ'], false));
            $currentSheet->setCellValue('F'.$currentRow, $fy['gate_mfr']);
            $currentSheet->setCellValue('G'.$currentRow, $fy['gate_model']);
            $currentSheet->setCellValue('H'.$currentRow, $fy['gate_motor_power']);
            $currentSheet->setCellValue('I'.$currentRow, $fy['gata_elev']);
            $currentSheet->setCellValue('J'.$currentRow, $fy['gate_h']);
            $currentSheet->setCellValue('K'.$currentRow, $fy['gate_wid']);
            $currentSheet->setCellValue('L'.$currentRow, gate_cont_type_option($fy['gate_cntl_typ'], false));
            $currentSheet->setCellValue('M'.$currentRow, gate_swit_sty_option($fy['gate_swit_sty'], false));
            $currentSheet->setCellValue('N'.$currentRow, $fy['gate_row_num']);
            $currentSheet->setCellValue('O'.$currentRow, $fy['gate_hole_num']);
            $currentSheet->setCellValue('P'.$currentRow, $fy['gate_svc_dt']);
            $currentRow++;
        }
        $currentSheet->getStyle('A1:P'.$currentRow)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $currentSheet->getStyle('A1:P'.$currentRow)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $currentSheet->getStyle('A1:P'.$currentRow)->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        $php_writer = new \PHPExcel_Writer_Excel5($php_excel);
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=闸门.xls");
        header('Cache-Control: max-age=0');
        $php_writer->save('php://output');
    }
}